<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue';
  import dayjs from 'dayjs';
  import { BasicTable, useTable } from '@/components/Table';
  import { useDrawer } from '@/components/Drawer';
  import { useModal } from '@/components/Modal';
  import { GetOrderListApi, GetReportIndexApi, OrderStatusApi } from '@/api/payment';
  import { Tag } from '@/components/InfoTag';
  import { jsonToSheetXlsx } from '@/components/Excel';
  import { getPaymentOrderColor } from '@/utils/order';
  import { OrderInfoModel, GrabModal } from './modal';

  const info = ref({
    allTotal: 0,
    allTotalAmount: 0,
    allSuccessTotal: 0,
    allSuccessAmount: 0,
  });

  const refresh = ref(30);

  let orderStatusArr = [];
  onMounted(async () => {
    orderStatusArr = await OrderStatusApi();
  });

  const formatOrderStatus = (key) => {
    for (let index = 0; index < orderStatusArr.length; index++) {
      const element = orderStatusArr[index];
      if (element.key == key) return element.value;
    }
  };

  const [registerTable, { getRawDataSource, getDataSource, reload }] = useTable({
    title: '代收订单管理',
    canResize: true,
    columns: [
      {
        title: '系统单号',
        dataIndex: 'orderNo',
        resizable: true,
      },
      {
        title: '商户单号',
        dataIndex: 'outTradeNo',
        resizable: true,
      },
      {
        title: '订单金额',
        dataIndex: 'amount',
        resizable: true,
      },
      {
        title: '通道类型',
        dataIndex: 'codeTitle',
        resizable: true,
      },
      {
        title: '收款账号',
        dataIndex: 'payAccount',
        resizable: true,
      },
      {
        title: '收款姓名',
        dataIndex: 'payName',
        resizable: true,
      },
      {
        title: '银行名称',
        dataIndex: 'bankName',
        resizable: true,
      },
      {
        title: '代付状态',
        dataIndex: 'orderStatus',
        resizable: true,
      },
      {
        title: '付款名称',
        dataIndex: 'name',
        resizable: true,
      },
      {
        title: '付款账号',
        dataIndex: 'account',
        resizable: true,
      },
      {
        title: '回调状态',
        dataIndex: 'callbackStatus',
        resizable: true,
      },
      {
        title: '结算状态',
        dataIndex: 'settlement',
        resizable: true,
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        resizable: true,
      },
      {
        title: '抢单时间',
        dataIndex: 'checkTime',
        resizable: true,
      },
      {
        title: '回调时间',
        dataIndex: 'callbackTime',
        resizable: true,
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 200,
        fixed: 'right',
      },
    ],
    bordered: true,
    showSelectionBar: false,
    showTableSetting: true,
    accordion: true, // 手风琴效果
    api: GetOrderListApi,
    fetchSetting: {
      listField: 'list',
    },
    useSearchForm: true,
    takeCare: '这是注意事项',
    formConfig: {
      labelWidth: 120,
      schemas: [
        {
          field: 'orderNo',
          label: '系统单号',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'outTradeNo',
          label: '商户单号',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'payAccount',
          label: '收款账号',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'payName',
          label: '收款姓名',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'account',
          label: '付款账号',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'namne',
          label: '付款姓名',
          component: 'Input',
          colProps: {
            span: 6,
          },
        },
        {
          field: 'codeTitle',
          label: '通道类型',
          component: 'ApiSelect',
          colProps: {
            span: 6,
          },
          componentProps: {
            api: GetReportIndexApi,
            resultField: 'list',
            labelField: 'title',
            valueField: 'title',
          },
        },
        {
          field: 'orderStatus',
          label: '代付状态',
          component: 'ApiSelect',
          colProps: {
            span: 6,
          },
          componentProps: {
            api: OrderStatusApi,
            labelField: 'value',
            valueField: 'key',
          },
        },
        {
          field: 'settlement',
          label: '结算状态',
          component: 'Select',
          colProps: {
            span: 6,
          },
          componentProps: {
            options: [
              {
                label: '未结算',
                value: 0,
              },
              {
                label: '已结算',
                value: 1,
              },
              {
                label: '代理反扣',
                value: 2,
              },
              {
                label: '系统返款',
                value: 3,
              },
              {
                label: '追扣中',
                value: 4,
              },
              {
                label: '追扣失败',
                value: 5,
              },
            ],
          },
        },
        {
          field: 'Refresh',
          label: '页面刷新时间',
          component: 'Select',
          colProps: {
            span: 6,
          },
          componentProps: {
            defaultValue: Number(localStorage.getItem('refresh')) || 30,
            options: [
              {
                label: '15秒',
                value: 15,
              },
              {
                label: '30秒',
                value: 30,
              },
              {
                label: '1分钟',
                value: 60,
              },
              {
                label: '5分钟',
                value: 300,
              },
            ],
          },
        },
      ],
    },
    afterFetch: () => {
      const data = getRawDataSource();
      info.value = {
        ...data,
      };
    },
  });

  const formatSettlement = (status) => {
    const statusText = ['未结算', '已结算', '代理反扣', '系统返款', '追扣中', '追扣失败'];
    return statusText[status];
  };

  const [registerGrabModal, { openModal }] = useModal();

  const [registerDrawer, { openDrawer }] = useDrawer();

  watch(
    () => refresh.value,
    () => {
      localStorage.setItem('refresh', refresh.value);
    },
  );

  const exportExcel = () => {
    jsonToSheetXlsx({
      data: getDataSource(),
      filename: '新订单审核导出.xlsx',
    });
  };

  const handleEdit = (record) => {
    openModal(true, {
      record,
      reload,
    });
  };

  const handleInfo = (record) => {
    openDrawer(true, {
      record,
    });
  };
</script>
<template>
  <main>
    <a-row :gutter="16">
      <a-col :span="24" style="margin-top: 16px">
        <BasicTable @register="registerTable">
          <template #toolbar>
            <Tag title="订单总数" color="red">{{ info.allTotal || 0 }}</Tag>
            <Tag title="订单总额" color="red">{{ info.allTotalAmount || 0 }}</Tag>
            <Tag title="成功总数" color="green">{{ info.allSuccessTotal || 0 }}</Tag>
            <Tag title="成功总额" color="green">{{ info.allSuccessAmount || 0 }}</Tag>
            <a-button @click="exportExcel" type="primary" size="small">筛选导出</a-button>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'create_time'">
              {{ dayjs(record.create_time * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-if="column.key === 'callbackTime'">
              {{
                record.callbackTime
                  ? dayjs(record.callbackTime * 1000).format('YYYY-MM-DD HH:mm:ss')
                  : '-'
              }}
            </template>
            <template v-if="column.key === 'checkTime'">
              {{ dayjs(record.checkTime * 1000).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
            <template v-if="column.key === 'agentRate'"
              >{{ record.agentGain }}/{{ record.agentRate }}</template
            >
            <template v-if="column.key === 'orderStatus'">
              <a-tag :style="getPaymentOrderColor(record.orderStatus)">{{
                formatOrderStatus(record.orderStatus)
              }}</a-tag>
            </template>
            <template v-if="column.key === 'payStatus'">
              <a-tag :color="record.payStatus == 0 ? 'red' : 'green'">{{
                record.payStatus == 0 ? '未支付' : '已支付'
              }}</a-tag>
            </template>
            <template v-if="column.key === 'callbackStatus'">
              <a-tag :color="record.callbackStatus == 0 ? 'red' : 'green'">{{
                record.callbackStatus == 0 ? '未回调' : '已回调'
              }}</a-tag>
            </template>
            <template v-if="column.key === 'settlement'">
              <a-tag :color="record.settlement == 0 ? 'red' : 'green'">{{
                formatSettlement(record.settlement)
              }}</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button
                  size="small"
                  v-if="record.orderStatus == 1 && record.payStatus == 0 && record.settlement == 0"
                  style="background-color: #bd3124; color: #fff"
                  @click="handleEdit(record)"
                  >点我处理打款</a-button
                >
                <a-button
                  size="small"
                  style="background-color: #4095e5; color: #fff"
                  @click="handleInfo(record)"
                  >详情</a-button
                >
              </a-space>
            </template>
          </template>
        </BasicTable>
      </a-col>
    </a-row>

    <OrderInfoModel @register="registerDrawer" />
    <GrabModal @register="registerGrabModal" />
  </main>
</template>
